package com.sikadwafastdaisfondturbo.pretloan.utils.imagecovert

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object ImageConvert {

    private fun covert(context: Context, file: File?, complete: (localPath: String?, bitmap: Bitmap?) -> Unit) {
        if (file == null) return

        try {
            val folder = "${context.filesDir.absolutePath}${File.separator}SikadwaPics"
            val imagePath = with(File(folder)) {
                if (!exists()) {
                    mkdirs()
                }
                "$absolutePath${File.separator}${System.currentTimeMillis()}.jpg"
            }

            val output = File(imagePath)
            val needCompress = ImageChecker.needCompress(300, file.absolutePath)
            val result = if (needCompress) ImageCompress(file, output, false).compress() else file

            val options = BitmapFactory.Options().apply { inJustDecodeBounds = false }
            val bitmap = BitmapFactory.decodeFile(result.absolutePath, options)

            complete.invoke(result.absolutePath, bitmap)

        } catch (e: IOException) {
            e.printStackTrace()
            complete.invoke(null, null)
        }
    }

    fun covert(context: Context, uri: Uri?, complete: (localPath: String?, bitmap: Bitmap?) -> Unit) {
        if (uri == null) return
        val file = toFile(context, uri)
        covert(context = context, file = file, complete)
    }

    @SuppressLint("Recycle")
    private fun toFile(context: Context, uri: Uri): File? {
        return try {
            val folder = "${context.filesDir.absolutePath}${File.separator}SikadwaPics_Ori"
            val imagePath = with(File(folder)) {
                if (!exists()) {
                    mkdirs()
                }
                "$absolutePath${File.separator}${System.currentTimeMillis()}.jpg"
            }

            val output = File(imagePath)
            val inputStream = context.contentResolver.openInputStream(uri) ?: return null
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(output)
            while (inputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            inputStream.close()
            File(imagePath)

        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
}